package com.uduemc.biso.node.module.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.entities.HBackupSetup;
import com.uduemc.biso.node.module.service.HBackupSetupService;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/h-backup-setup")
@Slf4j
public class HBackupSetupController {

	@Autowired
	private HBackupSetupService hBackupSetupServiceImpl;

	@GetMapping("/find-by-host-id-if-not-and-create/{hostId:\\d+}")
	public RestResult findByHostIdIfNotAndCreate(@PathVariable("hostId") long hostId) {
		HBackupSetup data = hBackupSetupServiceImpl.findByHostIdIfNotAndCreate(hostId);
		return RestResult.ok(data, HBackupSetup.class.toString());
	}

	/**
	 * 更新 HBackupSetup 数据
	 * 
	 * @param hBackupSetup
	 * @param errors
	 * @return
	 */
	@PostMapping("/update-by-primary-key")
	public RestResult updateByPrimaryKey(@Valid @RequestBody HBackupSetup hBackupSetup, BindingResult errors) {
		log.info("updateByPrimaryKey: " + hBackupSetup.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		HBackupSetup findOne = hBackupSetupServiceImpl.findOne(hBackupSetup.getId());
		if (findOne == null) {
			return RestResult.noData();
		}
		HBackupSetup data = hBackupSetupServiceImpl.updateByPrimaryKey(hBackupSetup);
		return RestResult.ok(data, HBackupSetup.class.toString());
	}

	/**
	 * 获取 当前时间 大于 start_at 时间，type 不为 0 的 数据列表
	 * 
	 * @return
	 */
	@GetMapping("/find-all-by-no-type-0-and-start-at-now")
	public RestResult findAllByNoType0AndStartAtNow() {
		List<HBackupSetup> list = hBackupSetupServiceImpl.findAllByNoType0AndStartAtNow();
		return RestResult.ok(list, HBackupSetup.class.toString(), true);
	}

}
